package com.workspace.js_website.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.workspace.js_website.bean.RespBean;
import com.workspace.js_website.bean.MetaBean;
import com.workspace.js_website.bean.ValidateCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

/**
 * 验证码相关服务
 */

@Service
public class SmsCodeService {

    private final String accessKeyId;
    private final String accessKeySecret;
    private final String singName;
    private String templateCode;

    public SmsCodeService() {
        accessKeyId = "LTAI4FztrZSumNP1kspNZAiK";
        accessKeySecret = "jV0OrHy6fiYAzWRAJlIz8xb4ew4RIZ";
        singName = "点控资讯";
        templateCode = "SMS_205700239";
    }

    public ValidateCode generate() {
        //用于生成一个60秒有效的6位验证码
        final int SMS_RANDOM_SIZE = 6;
        final int SMS_EXPIRE_SECOND = 60;

        String code = RandomStringUtils.randomNumeric(SMS_RANDOM_SIZE);
        return new ValidateCode(code, SMS_EXPIRE_SECOND);
    }

    public RespBean send(String mobile, String target, String code) {
        if (target.equals("register"))
            templateCode = "SMS_205700237";
        if (target.equals("findBakePassword"))
            templateCode = "SMS_205700236";

        //阿里云短信发送服务代码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", singName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject object = JSONObject.parseObject(response.getData());
            if (object.get("Message").equals("OK"))
                return new RespBean("", new MetaBean(200, "发送成功!"));
            else
                return new RespBean("", new MetaBean(400, "发送失败!"));
        } catch (ClientException e) {
            e.printStackTrace();
            return new RespBean("", new MetaBean(400, e.toString()));
        }
    }
}
